package org.jeecg.modules.cascv.image.service.merge.shengwushiyangui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.service.merge.ranshaogui.Ranshaogui2Service;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author贺弘烨
 * @Version 2022/3/21
 * description;
 */
@Slf4j
@Service
public class XiaoxinTongyongShengwuPeiyangXianweiImgService extends ImageService {
    @Value("${imageurl}")
    private  String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;

    @Value("${imageSaveDir}")
    private String imageSaveDir;
    //小型通用生物培养模块相机显微图片
    @Override
    public String idsNames() {
        return "6D1DH_48H,6D3DH_48H";
    }


    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if(intpackageNum!=0){
                log.error("当前包的包序号不是0开头，包序号为："+intpackageNum);
            }
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }
        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        String dataFrames = conJson.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
        String startEndFlag = conJson.getString(LaptopConstant.STARTEND_FLAG_MAP.get(idsName));
        startEndFlag = startEndFlag.split(";")[0];
        //dataFrames = (dataFrames.split(";")[1]).substring(2).trim();
        //dataFrames = dataFrames.substring(5,dataFrames.length()-9);



       dataFrames = dataFrames.split(";")[1].substring(2).trim();

        StringBuilder queue = LaptopConstant.imageData.get(key);
        composite(idsName, key, conJson, dataFrames, queue, startEndFlag,secondStr,subSecondStr);

        return null;
    }

    private boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String startEndFlag,String secondStr,String subSecondStr ) {
        int width = 2592;
        int height = 1944;
        while (dataFrames.endsWith("BA")) {//方法用于判断字符串是否以指定后缀结尾
            dataFrames = dataFrames.substring(0, dataFrames.length() - 2);
        }


        if (LaptopConstant.START_FLAG.equalsIgnoreCase(startEndFlag)){
            queue= new StringBuilder();
            dataFrames = StringUtils.substring(dataFrames, 16);
            queue.append(dataFrames);
            LaptopConstant.imageData.put(key, queue);
        }else if (null!=queue&&LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)){
            queue.append(dataFrames);
            while (queue.length() < 2592 * 1944 * 2) {
                queue.append("0");
            }
            while (queue.length() > 2592 * 1944 * 2) {
                queue.delete(queue.length() - 1, queue.length());
            }
            String imgHexStr = queue.toString();

            CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                long start = System.currentTimeMillis();
                byte[]  bytes = HexUtil.decodeHex(imgHexStr);
                String idStr = IdWorker.getIdStr();
                int png = LaptopConstant.nativeImageIO.write(bytes, height, width, imageSaveDir, idStr + ".png", "png");

                System.out.println("imageurl = " + imageurl);
                String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                //      System.out.println("imageUrl = " + imageUrl);
                content.put("imageUrl", imageUrl);
                content.put("idsName", idsName);
                //获取时间
                //    String secondStr = content.getString(LaptopConstant.SECOND_FIELD_MAP.get(idsName)).split(";")[1];
                //   String subSecondStr = content.getString(LaptopConstant.SUB_SECOND_FIELD_MAP.get(idsName)).split(";")[1];
                String[] split = secondStr.split(":");
                content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                //将图片添加到map
                content.put("key", key);
                log.info("小型通用生物培养显微图片"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");
                return content;
            },taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);

            LaptopConstant.imageData.remove(key);//清空图片数据
        }else {
            if(null==queue){
//                log.info(idsName+"开始传入的数据不是完整的，没有01B开始标志。");
                return false;
            }
            queue.append(dataFrames);
            LaptopConstant.imageData.put(key, queue);
        }
        return true;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");//D:\pc_workspace\shengwushiyan2\
        List<String> strings = FileUtil.readUtf8Lines("E:\\图像数据\\cut\\生命生态\\T20230102132320_0001_0063_F1_00_6DCD_2024_0048_48_6D1D_000000000.txt");
        XiaoxinTongyongShengwuPeiyangXianweiImgService xianweiImgService = new XiaoxinTongyongShengwuPeiyangXianweiImgService();

        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            xianweiImgService.merge(jsonObject, "6D1DH_48H", "6D1DH_48H");
        }

    }

}
